package com.steve.xfood.service.impl;

import com.steve.xfood.config.WeChatAccountConfig;
import com.steve.xfood.dto.OrderDTO;
import com.steve.xfood.service.PushMessageService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author steve
 * @date 2020/5/27 16:04
 */
@Service
@Slf4j
public class PushMessageServiceImpl implements PushMessageService {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WeChatAccountConfig accountConfig;

    @Override
    public void orderStatus(OrderDTO orderDTO) {
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        //设置用户openid
        templateMessage.setToUser(orderDTO.getBuyerOpenid());
        //设置消息模板id
        templateMessage.setTemplateId(accountConfig.getTemplateId().get("orderStatus"));
        //封装模板数据
        List<WxMpTemplateData> data = Arrays.asList(
                new WxMpTemplateData("first","亲，请记得收获"),
                new WxMpTemplateData("keyword1","微信点餐"),
                new WxMpTemplateData("keyword2","13816812345"),
                new WxMpTemplateData("keyword3", orderDTO.getOrderId()),
                new WxMpTemplateData("keyword4",orderDTO.getOrderStatusEnum().getMsg()),
                new WxMpTemplateData("keyword5","￥"+orderDTO.getOrderAmount()),
                new WxMpTemplateData("remark","欢迎再次光临")
        );
        //设置模板数据
        templateMessage.setData(data);
        /*
            1.在完结订单里加入消息推送
            2.之所以在service里try...catch异常，原因有：
                1)假如不在service里try...catch异常，到了完结订单的逻辑，如果这时出异常了，那么订单会因为消息推送失败而回滚数据。
                  这是不合理的，消息推送只是一个附加功能，不能因为附加功能出错而导致整个订单都回滚
                2)因此在service里进行try...catch异常，就不会影响完结订单的逻辑
         */
        try {
            //发送消息
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.error("【微信消息模板推送】 发送失败{}" + e);
        }
    }
}
